package com.jubaozan.framework.sentinel.springmvc.listener;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.csp.sentinel.cluster.flow.rule.ClusterFlowRuleManager;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.alibaba.csp.sentinel.util.AppNameUtil;
import com.jubaozan.framework.sentinel.constant.RuleKeyConstant;
import com.jubaozan.framework.sentinel.listener.AbstractRulePropertyListener;
import com.jubaozan.framework.sentinel.listener.RedisRulePublisher;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author jiangjinwu
 * @version 1.0
 * @since 2025/7/15 10:37
 */

@Slf4j
@Component
public class FlowPropertyListener extends AbstractRulePropertyListener<FlowRule> {

    @Autowired
    RuleKeyConstant ruleKeyConstant;

    public FlowPropertyListener() {
        super(FlowRule.class);
    }

    @Override
    protected void doLoad(List<FlowRule> conf) {
        FlowRuleManager.loadRules(conf);
        Optional.ofNullable(conf).ifPresent(rules -> {
                List<FlowRule> clusterConf = rules.stream().filter(rule -> rule.getClusterConfig() != null && rule.isClusterMode())
                    .collect(Collectors.toList());
                if (CollUtil.isNotEmpty(clusterConf)) {
                    String nameSpace = AppNameUtil.getAppName();
                    ClusterFlowRuleManager.registerPropertyIfAbsent(nameSpace);
                    ClusterFlowRuleManager.loadRules(nameSpace, clusterConf);
                }
            }
        );

        log.info("接收到限流配置加载: {}", conf);
    }


    @Override
    protected String getRedisKey() {
        return ruleKeyConstant.getFlowRuleKey();
    }

}
